package com.security.SecutiryTools;

import android.util.Base64;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by stathis on 6/1/14.
 */
public class Aes {


    public static byte[] MD5(byte[] input) throws NoSuchAlgorithmException {


        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(input);

        return  thedigest;
    }


    public static String encrypt(String clear, byte[] raw) throws Exception {
        byte[] temp;
        temp=clear.getBytes("UTF-8");

        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(temp);
        String result= Base64.encodeToString(encrypted,Base64.DEFAULT);

        return result;
    }

    public static String decrypt(String encrypted, byte[] raw) throws Exception {
        byte[] temp= Base64.decode(encrypted,Base64.DEFAULT);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(temp);
        String result = new String(decrypted);
        return result;

    }

}
